import React, { Component } from 'react';
import { Button, Modal as RModal, Toast, WingBlank } from 'antd-mobile';
import {
  AsyncStorage,
  Image,
  Modal,
  ScrollView,
  StatusBar,
  Text,
  TouchableHighlight,
  TouchableWithoutFeedback,
  View
} from 'react-native';
import styles from './style';
import ImageViewer from 'react-native-image-zoom-viewer';
import { Video } from 'expo';
import VideoPlayer from '@expo/videoplayer';

const alert = RModal.alert;

// fix touch to scroll background page on iOS
// https://github.com/ant-design/ant-design-mobile/issues/307
// https://github.com/ant-design/ant-design-mobile/issues/163
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

export default class DetailScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: '',
      modalShow: false,
      imageUrls: [],
      imageIndex: 0,
    };
    this.renderContent = this.renderContent.bind(this);
    this.imageView = this.imageView.bind(this);
    this.closeImageView = this.closeImageView.bind(this);
  }

  static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;
    return {
      headerLeft: (
        <TouchableWithoutFeedback onPress={() => {
          Toast.hide();
          navigation.goBack();
        }}>
          <View>
            <Image style={{ width: 23, height: 23, tintColor: '#fff', marginLeft: 10 }}
                   source={require('../../images/back.png')}
                   resizeMode="cover"
            />
          </View>
        </TouchableWithoutFeedback>
      ),
      headerRight: (
        <TouchableWithoutFeedback onPress={() => params.clickRight()}>
          <View>
            <Image style={{ width: 23, height: 23, tintColor: '#fff', marginRight: 10 }}
                   source={require('../../images/heart.png')}
                   resizeMode="cover"
            />
          </View>
        </TouchableWithoutFeedback>
      ),
      headerTitleStyle: {
        color: '#fff',
      },
      headerStyle: {
        backgroundColor: '#ed4040'
      },
    };
  };

  async componentDidMount() {
    const navigation = this.props.navigation;
    this.props.navigation.setParams({
      clickLeft: navigation.goBack,
      clickRight: this.showActionSheet.bind(this)
    });
    const { id } = navigation.state.params;
    Toast.success(id, 3, f => f, false);
    Toast.loading('加载中...', 999999999999);
    let f = await fetch(`https://ecmad.com/toutiao/api/article/detail?id=${id}`, {
      method: 'GET',
    }).catch(() => {
      Toast.offline('网络异常', 2, f => f, false);
    });
    let res = await f.json();
    Toast.hide();
    this.setState({
      data: res.data,
    });
  }

  showActionSheet = () => {
    const { data } = this.state;
    alert('', <Text style={{ fontSize: 20, lineHeight: 60, textAlign: 'center' }}>确定加入收藏？</Text>, [
      { text: '取消', onPress: f => f },
      {
        text: '确定', onPress: async () => {
        AsyncStorage.getItem('collection', (err, result) => {
          if (err || !result) {
            AsyncStorage.setItem('collection', JSON.stringify([data.id]));
          } else {
            let ids = [];
            try {
              ids = JSON.parse(result);
            } catch (ex) {
              console.log(ex);
            }
            if (ids.includes(data.id)) {
              Toast.info('您已经收藏过了', 2, f => f, false);
              return false;
            }
            ids.push(data.id);
            AsyncStorage.setItem('collection', JSON.stringify(ids), () => {
              Toast.info('收藏成功', 2, f => f, false);
            });
          }
        })
      }
      },
    ]);
  };

  imageView(img) {
    this.setState({
      modalShow: true,
      imageUrls: [{ url: img }],
      imageIndex: 0,
    })
  }

  closeImageView() {
    this.setState({
      modalShow: false,
    });
  }

  renderContent(content = '') {
    const arr = content.split(/\n|\s+/img).filter(f => f);
    return arr.map((item, index) => {
        if (/^{{/img.test(item)) {
          return (
            <TouchableHighlight onPress={() => this.imageView(item.slice(2, -2))} key={`images-${index}`}>
              <Image source={{ uri: item.slice(2, -2) }} key={index} resizeMode={'contain'}
                     style={{ width: '100%', height: 260, marginTop: 10, marginBottom: 10 }} />
            </TouchableHighlight>
          )
        } else if (/^\[\[/img.test(item)) {
          return (
            <View style={{ marginTop: 15 }} key={`video-${index}`}>
              <VideoPlayer
                videoProps={{
                  shouldPlay: false,
                  resizeMode: Video.RESIZE_MODE_CONTAIN,
                  source: {
                    uri: item.slice(2, -2),
                  },
                }}
                showControlsOnLoad={true}
                isPortrait={true}
                playFromPositionMillis={0}
              />
            </View>
          );
        } else {
          return <Text style={styles.line} key={index}>{item}</Text>
        }
      }
    );
  }

  render() {
    const { state, navigate } = this.props.navigation;
    const { title } = state.params;
    const { data, modalShow, imageUrls } = this.state;
    return (
      <ScrollView style={styles.detail}>
        <StatusBar barStyle="light-content" />
        <WingBlank>
          <Text style={styles.title}>
            {title}
          </Text>
          <View style={styles.numContainer}>
            <View style={{ width: 40, marginRight: 8 }}>
              <Image source={{ uri: data.logo }} resizeMode={'contain'} style={{ width: 30, height: 30, }} />
            </View>
            <View style={{ flex: 1 }}>
              <Text style={{ fontSize: 14, color: '#666', marginBottom: 3 }}>{data.public_name}</Text>
              <Text style={{ fontSize: 12, color: '#666' }}>微信公众号：{data.public_num}</Text>
            </View>
            <View style={{ width: 50 }}>
              <Button type="primary" inline size="small" onClick={() => navigate('Source', {
                name: data.public_name,
                num: data.public_num,
                info: data.info,
                logo: data.logo,
              })}>
                <Text style={{ fontSize: 12 }}>进入</Text>
              </Button>
            </View>
          </View>
          <View style={styles.content}>
            {this.renderContent(data.content)}
          </View>
          <Text style={styles.line}>
              内容转载自：{data.public_name}
            </Text>
          <View style={styles.copyright}>
            <Text style={styles.copyrightTitle}>转载声明</Text>
            <Text style={styles.copyrightDetail}>本站系本网编辑转载，转载目的在于传递更多信息，并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题，请在30日内与本网联系，我们将在第一时间删除内容！[声明]本站文章版权归原作者所有 内容为作者个人观点 本站只提供参考并不构成任何投资及应用建议。本站拥有对此声明的最终解释权。</Text>
          </View>
          </WingBlank>
          <Modal animationType={"slide"} visible={modalShow} transparent={true}>
              <ImageViewer imageUrls={imageUrls} index={0} onClick={this.closeImageView} />
          </Modal>
      </ScrollView>
    );
  }
}
